class User {
  constructor() {
    this.templateList = load('templateList') || [];
    this.taskList = load('taskList') || [];
    this.timeBoxList = load('timeBoxList') || [];
    this.settingList = {
      startDayTime: {
        title: '每天从第几小时开始',
        type: 'number',
        value: 0,
        check: x => !isNaN(x) && x >= 0 && x < 24,
      },
      areaRow: {
        title: 'box行数',
        type: 'number',
        value: 3,
        check: x => !isNaN(x) && x === Math.floor(x),
      },
      brightness: {
        title: '明亮度',
        type: 'number',
        value: 100,
        check: x => !isNaN(x) && x >= 5,
      },
      hueRotate: {
        title: '色相旋转',
        type: 'number',
        value: 0,
        check: x => !isNaN(x),
      }
    };
    for (let key in this.settingList) {
      let setting = this.settingList[key];
      setting.toJSON = () => setting.value;
    }
    let settingData = load('settingList');
    for (let key in settingData) {
      this.settingList[key].value = settingData[key];
    }
  }

  applyTemplate(template) {
    this.timeBoxList = template.timeList.map(
      (timePeriod) => ({
        ...timePeriod,
        task: '',
      })
    );
    this.save('timeBoxList');
  }

  save(key) {
    if (this[key] === undefined)
      throw `${key} is undefined`;
    save(key, this[key]);
  }
}

function load(key, reviver) {
  let dataJSON = localStorage.getItem(key);
  if (dataJSON === null)
    return null;
  return JSON.parse(dataJSON, reviver);
}

function save(key, obj) {
  localStorage.setItem(key, JSON.stringify(obj));
}

export default new User();